// 102. 二叉树的层序遍历

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function levelOrder(root: TreeNode | null): number[][] {
  if (!root) return [];

  const result: number[][] = [];
  const stack: [TreeNode | null, number][] = [[root, 0]];
  // stack.push(root)
  while (stack.length) {
    // const n = stack.length
    // const level: number[] = [];
    // for (let i = 0; i < n; ++i) {
    //     const node: TreeNode = stack.pop()
    //     level.push(node.val)
    //     if (node.left) stack.push(node.left)
    //     if (node.right) stack.push(node.right)

    // }

    // result.push(level)
    const [n, level] = stack.shift();
    if (!result[level]) {
      result[level] = [n.val];
    } else {
      result[level].push(n.val);
    }
    n.left && stack.push([n.left, level + 1]);
    n.right && stack.push([n.right, level + 1]);
  }
  return result;
}
